<template>
	<view class="page">
		<view class="login">
			<view class="login-title">
				<text>{{ title }}</text>
			</view>

			<uni-forms :modelValue="formData" :rules="formRules" ref="formRef">
				<uni-forms-item required name="username" label="账号"><uni-easyinput type="text" v-model="formData.username" placeholder="请输入账号" /></uni-forms-item>
				<uni-forms-item required name="password" label="密码"><uni-easyinput type="password" v-model="formData.password" placeholder="请输入密码" /></uni-forms-item>
				<uni-forms-item name="save"><uni-data-checkbox multiple v-model="formData.save" :localdata="checkOptions" /></uni-forms-item>
			</uni-forms>

			<button :loading="showBtnLoading" hover-class="hover-class" class="login-button" @tap="authLogin">登录</button>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			formData: {
				username: '',
				password: '',
				save: ''
			},
			formRules: {
				username: {
					rules: [
						{
							required: true,
							errorMessage: '请输入账号'
						}
					]
				},
				password: {
					rules: [
						{
							required: true,
							errorMessage: '请输入密码'
						}
					]
				}
			},
			checkOptions: [
				{
					value: '1',
					text: '是否记住密码?'
				}
			],
			title: '河南航空货运管理助手',
			showBtnLoading: false
		}
	},
	onLoad() {
		const user = uni.getStorageSync('user')
		if (user && Object.keys(user).length > 0) {
			this.formData.username = user.username
			this.formData.password = user.password
			this.formData.save = user.save
		}
	},
	onReady() {
		this.$refs.formRef.setRules(this.formRules)
	},
	methods: {
		async authLogin() {
			this.showBtnLoading = true

			this.$refs.formRef
				.validate()
				.then(async res => {
					console.log('表单数据信息：', res)

					const params = {
						username: this.formData.username,
						password: this.formData.password,
						appid: 'h5appid20210818',
						platform: 'h5_app'
					}

					console.log('this.formData.save: ', this.formData.save)

					if (this.formData.save.length > 0) {
						const user = Object.assign({}, params, {
							save: this.formData.save
						})
						uni.setStorageSync('user', user)
					} else {
						uni.setStorageSync('user', '')
					}

					try {
						const res = await uni.$uu.Api.getUserAuth(params)

						console.log(res)

						if (res.code === 100) {
							uni.setStorageSync('loginRes', res.content)
							uni.showToast({
								icon: 'success',
								title: '登录成功'
							})
							setTimeout(() => {
								const url = '/pages/risk/table/index'
								uni.redirectTo({
									url
								})
							}, 1500)
						}
						this.showBtnLoading = false
					} catch (e) {
						console.log(e)
						this.showBtnLoading = false
					}
				})
				.catch(err => {
					console.log('表单错误信息：', err)
					this.showBtnLoading = false
				})
		}
	}
}
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
